<?php
/**
 * Created by PhpStorm.
 * User: bzyy
 * Date: 2015年11月5日14:28:34
 *
 */

class Goods_draftModel extends BaseModel
{

    public $table = 'goods_draft';
    public $prikey = 'id';

    public $data = array();

    public $goods_id = 0;
    public $gt_id = 0;
    public $user_id=0;
    public $store_id = 0;

    public $check_goods_image_path = true;//是否要验证检测商品图片路径问题


    /**
     * @param $data
     * @param $step
     *
     */
    public function savedata($data,$step)
    {
        $flag = $this->check_data($data,$step);
        if(!$flag)
        {
            return false;
        }

        if($step == 1)
        {
            return $this->save_1($data);
        }
        elseif($step == 2)
        {
            return $this->save_2($data);
        }
        elseif($step == 3)
        {
            return $this->save_3($data);
        }
        elseif($step == 4)
        {
            return $this->save_4($data);
        }
        elseif($step == 5)
        {
            return $this->save_5($data);
        }

        return $this->data;
    }

    /*
     * 检测对应的商品等信息是否是自己的
     */
    public function check_owner($user_id,$goods_id,$gp_id)
    {
        if($user_id==0)
        {
            return false;
        }
        if($goods_id == 0 && $gp_id == 0)
        {
            return false;
        }

        if($gp_id)
        {
            $model_graft = m('goods_draft');
            $info = $model_graft->get_info($gp_id);
            if(empty($info) || $info['user_id']!=$user_id)
            {
                return false;
            }
        }

        if($goods_id)
        {
            $model_goods = m('goods');
            $info = $model_goods->get_info($goods_id);
            if(empty($info) || $info['store_id'] != $user_id)
            {
                return false;
            }
        }

        return true;

    }

    /**
     * @param $data
     *
     * 保存数据第一步
     */
    protected function save_1($data)
    {


        $flag_t = !$this->goods_id;
        //全新添加的模式
        if($flag_t)
        {
            $post_data = array('user_id'=>$this->user_id,'store_id'=>$this->store_id,'c_time'=>time());
            $post_data['data_1'] = serialize($data);
            if($this->gt_id)
            {
                $flag = $this->edit($this->gt_id,$post_data);
                $flag = $flag?$this->gt_id:0;
            }
            else{
                $flag = $this->add($post_data);
            }

            if(!$flag)
            {
                $this->_error('添加的时候出错了');
                return false;
            }

            return $flag;

        }
        else
        {
            $gkey = $this->getkey(1);
            $gdata = array();
            foreach($gkey as $val)
            {
                $gdata[$val] = $data[$val];
            }

            $model_goods = m('goods');
            $gdata['last_update'] = time();
            $flag = $model_goods->edit($this->goods_id,$gdata);
            //对关联的维护--待做

            $model_goods->unlinkRelation('belongs_to_gcategory', $this->goods_id);
            if ($data['sgcate_id'])
            {
                $model_goods->createRelation('belongs_to_gcategory', $this->goods_id, $data['sgcate_id']);
            }
            return $flag;
        }
    }

    protected function save_2($data)
    {

        $flag_t = $this->gt_id;
        //临时表的修改情况
        if($flag_t)
        {
            $post_data = array('data_2'=>serialize($data));
            $post_data['m_time'] = time();

            $flag = $this->edit($this->gt_id,$post_data);
            if(!$flag)
            {
                $this->_error('数据保存时发生错误');
                return false;
            }

            return $flag;
        }
        else
        {
            //保存基本数据内容
            $g_data = array();

            $g_data['brand_id'] = $data['brand_id'];
            $g_data['goods_name'] = $data['goods_name'];
            $g_data['tags'] = $data['tags'];
            $g_data['introduction'] = $data['introduction'];
            $g_data['brand'] = $data['brand'];
            $g_data['last_update'] = time();
            $model_goods = m('goods');
            $f = $model_goods->edit($this->goods_id,$g_data);
            if(!$f)
            {
                $this->_error('保存商品基本信息时出错');
                return false;
            }

            //保存属性的内容
            //提取atrdata
            $attr_data = array();
            $attr_data[] = array('name'=>'产地','value'=>$data['attr_1'],'pid'=>'1');
            $attr_data[] = array('name'=>'商品材质','value'=>$data['attr_2'],'pid'=>'2');
            $attr_data[] = array('name'=>'商品保养','value'=>$data['attr_3'],'pid'=>'3');

            $flag = $this->addattr($attr_data,$this->goods_id);
            if(!$flag)
            {
                return false;
            }

            return true;

        }
    }


    protected function save_3($data)
    {
        $flag_t = $this->gt_id;
        if($flag_t)
        {
            $post_data = array('data_3'=>serialize($data));
            $post_data['m_time'] = time();

            $flag = $this->edit($this->gt_id,$post_data);

            if(!$flag)
            {
                $this->_error('数据保存时发生错误');
                return false;
            }
            return $flag;
        }
        else
        {
            //更新图片信息的处理
            $flag = $this->add_goods_images($data['image_list'],$data['default_image'],$this->goods_id);
            if(!$flag)
            {
                return false;
            }
            //保存默认的图片信息
            $model_goods = m('goods');
            $flag = $model_goods->edit($this->goods_id,array('default_image'=>$data['default_image']));
            if(!$flag)
            {
                $this->_error('更新商品信息时发生错误');
                return false;
            }
            return true;

        }
    }


    protected function save_4($data)
    {
        $flag_t = $this->gt_id;
        if($flag_t)
        {
            $post_data = array('data_4'=>serialize($data));
            $post_data['m_time'] = time();

            $flag = $this->edit($this->gt_id,$post_data);
            if(!$flag)
            {
                $this->_error('数据保存时发生错误');
                return false;
            }
            return $flag;
        }
        else
        {
            $this->begin();
            $model_goods = m('goods');
            $g_data = array();
            $g_keys = $this->getkey(4);
            unset($g_keys['default_spec']);
            foreach($g_keys as $v)
            {
                $g_data[$v] = $data[$v];
            }

            //保存规格的内容
            $flag = $this->addspec($data['sku_data'],$this->goods_id);
            if(!$flag)
            {
                $this->rollback();
                return false;
            }
            //更新商品的默认规格
            $g_data['price'] = $flag['price'];

            $g_data['discount_price'] = $flag['discount_spec_price'];
            $g_data['default_spec'] = $flag['spec_id'];
            $g_data['last_update'] = time();
            $flag = $model_goods->edit($this->goods_id,$g_data);
            if(!$flag)
            {
                $this->rollback();
                $this->_error('数据保存时发生错误');
                return false;
            }

            $this->commit();
            return true;

        }
    }


    protected function save_5($data)
    {
        $flag_t = $this->gt_id;
        if($flag_t)
        {
            $post_data = array('data_5'=>serialize($data));
            $post_data['m_time'] = time();

            $flag = $this->edit($this->gt_id,$post_data);
            if(!$flag)
            {
                $this->_error('数据保存时发生错误');
                return false;
            }
            return $flag;
        }
        else
        {
            $model_goods = m('goods');
            $g_data = array('description'=>$data['description']);
            $g_data['last_update'] = time();
            $flag = $model_goods->edit($this->goods_id,$g_data);
            if(!$flag)
            {
                $this->_error('数据保存时发生错误');
                return false;
            }
            return $flag;

        }
    }



    public function getDataInfo($step)
    {
        $data = array();

        if($this->goods_id)
        {
            $model_goods = m('goods');

            $cond = array();
            $fields = $this->getkey($step);
            $cond['conditions'] = "goods_id='{$this->goods_id}'";
            $cond['fields'] = implode(',',$fields);
            $data =$model_goods->get($cond);

            if(empty($data))
            {
                $this->_error('商品信息不存在');
                return false;
            }

            if($step == 1)
            {

                $temp = $model_goods->getRelatedData('belongs_to_gcategory', $this->goods_id, array(
                    'fields' => 'category_goods.cate_id',
                ));

                $temp_data = array();
                foreach($temp as $val)
                {
                    $temp_data[] = $val['cate_id'];
                }
                $data['sgcate_id'] = $temp_data;


            }
            elseif($step == 2)
            {

                //找到附加属性的数据
                $model_attr = m('goodsattr');
                $temp = (array)$model_attr->find("goods_id='{$this->goods_id}' and attr_id in (1,2,3) ");
                foreach($temp as $val)
                {
                    $data["attr_{$val['attr_id']}"] = $val['attr_value'];
                }

            }
            elseif($step == 3)
            {
                //商品图片列表
                $model_img = m('goodsimage');
                $temp = (array)$model_img->find(array(
                    'conditions'=>"goods_id='{$this->goods_id}'",
                    'order'=>"sort_order"
                ));
                $listimg = array();
                foreach($temp as $val)
                {
                    $listimg[] = $val['image_url'];
                }

                $data['image_list'] = $listimg;
            }
            elseif($step == 4)
            {
                //sku_data
                //货号和库存的问题,找到一个的默认的属性
                $model_spec = m('goodsspec');
                $spec_info = $model_spec->get_info($data['default_spec']);

                if(!empty($spec_info))
                {
                    $data['sku_g'] = $spec_info['sku'];
                    $data['stock_g'] = $spec_info['stock'];
                    $data['price_g'] = $spec_info['price'];
                }
                //
                $temp_spec = $model_spec->find("goods_id='{$this->goods_id}'");
                $sku_data = array();
                foreach($temp_spec as $key=>$val)
                {
                    if(empty($val['spec_1']) && empty($val['spec_2']) )
                    {
                        continue;
                    }
                    $sku_data[$key] = $val;
                }
                $data['sku_data'] = $sku_data;



            }
            elseif($step == 5)
            {

            }


        }
        elseif($this->gt_id)
        {
            $info = $this->get($this->gt_id);
            $key = "data_{$step}";
            if(isset($info[$key]))
            {
                $data = unserialize($info[$key]);
            }

            if($step == 4)
            {
                if(!isset($data['spec_qty']))
                {
                    $data['spec_qty'] = 2;
                    $data['spec_name_1'] = '颜色';
                    $data['spec_name_2'] = '尺码';
                }
                if(isset($data['sku_data']))
                {
                    $spec = $data['sku_data'][0];
                    $data['price_g'] = $spec['price'];
                    $data['sku_g'] = $spec['sku'];
                    $data['stock_g'] = $spec['stock'];
                    $data['discount_price'] = $spec['discount_spec_price'];
                }
            }

        }

        if(isset($data['sku_data']))
        {
            //统计对应的有效参数处理
            $temp['spec_qty'] = $data['spec_qty'];

            $temp['spec_name_1'] = $data['spec_name_1'];
            $temp['spec_name_2'] = $data['spec_name_2'];

            $sku_data = array();
            foreach($data['sku_data'] as $val)
            {
                if(empty($val['spec_1']) && empty($val['spec_2']))
                {
                    continue;
                }
                $sku_data[] = $val;
            }

            if(!empty($sku_data))
            {
                $temp['specs'] = $sku_data;
                $data['json_sku_data'] = $this->encode_json($temp);
            }

        }

        return $data;
    }

    function encode_json($str) {
        return urldecode(json_encode($this->url_encode($str)));
    }

    /**
     *
     */
    function url_encode($str) {
        if(is_array($str)) {
            foreach($str as $key=>$value) {
                $str[urlencode($key)] = $this->url_encode($value);
            }
        } else {
            $str = urlencode($str);
        }

        return $str;
    }

    /**
     * @param $data
     *
     * 把临时表的数据改变成为数据库中的数据
     *
     */
    public function saveDb()
    {
        $info = $this->get_info($this->gt_id);

        $user_id = $info['user_id'];
        $store_id = $info['store_id'];

        $data_1 = (array)unserialize($info['data_1']);
        $data_2 = (array)unserialize($info['data_2']);
        $data_3 = (array)unserialize($info['data_3']);
        $data_4 = (array)unserialize($info['data_4']);
        $data_5 = (array)unserialize($info['data_5']);

        $temp_data = array_merge($data_1,$data_2,$data_3,$data_4,$data_5);

        $goods = array();//
        $g_keys = array('goods_name','introduction','description','cate_id',
            'cate_id2','cate_name','cate_name2','spec_name_1','spec_name_2',
            'default_image','cate_id_1','cate_id_2','cate_id_3','cate_id_4',
            'cate_id2_1','cate_id2_2','cate_id2_3','cate_id2_4','tags',
            'market_price','supply_price','rate','if_custom','discount_price',
            'is_act','post_template_id','post_template_value','brand_id','brand');
        $goods['store_id'] = $store_id;
        foreach($g_keys as $val)
        {
            $goods[$val] = $temp_data[$val];
        }
        $goods['price'] = $temp_data['price_g'];

        //对数据进行处理一下
        $t_mp = array();
        $t_mp[] = $temp_data['spec_name_1'];
        $t_mp[] = $temp_data['spec_name_2'];
        $t_mp = array_filter($t_mp);
        $goods['spec_qty'] = count($t_mp);


        //规格数据
        $sku_data = $temp_data['sku_data'];

        if(empty($sku_data))//生成默认的一个规格数据
        {
            $temp = array();
            $temp['spec_1'] = '';
            $temp['spec_2'] = '';
            $temp['price'] = $goods['price_g'];
            $temp['stock'] = $goods['stock_g'];
            $temp['sku'] = 20;
            $temp['spec_supply_price'] = 30;
            $temp['discount_spec_price'] = 40;
            $temp['is_show_discount'] = 2;

            $sku_data[] = $temp;
        }

        //图片数据
        $image_list = $temp_data['image_list'];

        //属性的数据
        $attr_data = array();
        $attr_data[] = array('name'=>'产地','value'=>$temp_data['attr_1'],'pid'=>1);
        $attr_data[] = array('name'=>'商品材质','value'=>$temp_data['attr_2'],'pid'=>2);
        $attr_data[] = array('name'=>'商品保养','value'=>$temp_data['attr_3'],'pid'=>3);

        $data = array();
        $data['goods'] = $goods;
        $data['sku_data'] = $sku_data;
        $data['image_list'] = $image_list;
        $data['attr_data'] = $attr_data;
        $data['sgcate_id'] = (array)$temp_data['sgcate_id'];

        return $data;

    }

    /**
     * @param $data
     * 把商品添加到db数据库中去
     *
     * 商品主表
     * 商品规格表
     * 商品图片表
     * 商品统计信息表
     * 商品的附加分类的处理
     *
     * 这里的数据应该是处理好的数据
     *
     */
    public function addDb($data)
    {
        //print_r($data);
        $this->begin();
        //添加商品的图片
        $goods = $data['goods'];
        $goods['add_time'] = time();
        $model_goods = m('goods');
        $goods_spec_name = array();
        $goods_spec_name[] = $goods['spec_name_1'];
        $goods_spec_name[] = $goods['spec_name_2'];
        $goods_spec_name = array_filter($goods_spec_name);
        $goods['spec_qty'] = count($goods_spec_name);

        $goods_id = $model_goods->add($goods);

        if(!$goods_id)
        {
            $this->_error('添加商品时出错误');
            return false;
        }

        $f = $this->addspec($data['sku_data'],$goods_id);
        if(!$f)
        {
            return false;
        }

        $spec_id = $f['spec_id'];


        //删除无效的其他属性,找到上传的信息内容
        $model_file = m('uploadedfile');
        $temp_img = $model_file->find("item_id='{$this->gt_id}' and belong=4 ");
        $temp_imgs = array();
        foreach($temp_img as $val)
        {
            $temp_imgs[$val['file_path']] = $val['file_id'];
        }

        $model_img = m('goodsimage');
        $temp = array('goods_id'=>$goods_id);

        $images_list = array();
        //添加图片信息
        foreach($data['image_list'] as $val)
        {
            $images_list[] = $val;
            $temp['image_url'] = $val;
            $temp['thumbnail'] = $val;
            $temp['source_img'] = '';
            $temp['sort_order'] = 0;
            $temp['file_id'] = isset($temp_imgs[$val])?$temp_imgs[$val]:0;

            $f = $model_img->add($temp);
            if(!$f)
            {
                $this->_error('处理图片列表的时候出错了');
                return false;
            }

        }

        $f = $this->addattr($data['attr_data'],$goods_id);
        if(!$f)
        {
            return false;
        }


        //加入商品的关联分类
        if(!empty($data['sgcate_id']))
        {
            $temp_cates = array();
            foreach($data['sgcate_id'] as $val)
            {
                $temp_cates[$val] = array('cate_id'=>$val);
            }
            $model_goods->createRelation('belongs_to_gcategory',$goods_id,$temp_cates);
        }


        //规格等商品信息的回写
        $model_goods->edit($goods_id,array('default_spec'=>$spec_id));


        //添加商品的统计信息
        $sql = "INSERT INTO `{$this->_prefix}goods_statistics` (goods_id) VALUES ({$goods_id})";
        $this->query($sql);

        //删除当前记录
        $sql = "delete from {$this->_prefix}goods_draft where id='{$this->gt_id}' limit 1";
        $this->query($sql);

        //更新附件对应的信息内容。
        if(!empty($images_list))
        {
            $goods_belong = BELONG_GOODS;
            $sql = "update {$this->_prefix}uploaded_file set belong='{$goods_belong}',item_id='{$goods_id}' where item_id='{$this->gt_id}' and belong=4 and file_path in ('".implode("','",$images_list) ."')";

            $f = $this->query($sql);
            if(!$f)
            {
                $this->_error("信息处理失败");
                $this->rollback();
                return false;
            }
        }

        //更新商品详情图片
        $sql = "update {$this->_prefix}uploaded_file set item_id='{$goods_id}' where belong='5' and item_id='{$this->gt_id}' ";
        $this->query($sql);

        $this->goods_id = $goods_id;
        $this->gt_id = 0;

        $this->commit();
        return $goods_id;

    }


    /**
     * @param $spec_data
     * @param $goods_id
     * @return array|bool
     *
     * 保存规格数据
     */
    protected function addspec($spec_data,$goods_id)
    {
        //添加商品规格信息
        $model_spec = m('goodsspec');

        $temp = array();
        $temp['goods_id'] = $goods_id;

        /**
         * 找到此商品的所有信息
         *
         */
        $oldspec = (array)$model_spec->find("goods_id='{$goods_id}'");



        $spec_id = 0;
        $spec = array();
        $yes_spec_ids = array(0);
        foreach($spec_data as $key=> $val)
        {
            $spec_id = array_key_exists($key,$oldspec)?$key:0;

            $temp['spec_1'] = $val['spec_1'];
            $temp['spec_2'] = $val['spec_2'];
            $temp['price'] = $val['price'];
            $temp['stock'] = $val['stock'];
            $temp['sku'] = $val['sku'];
            $temp['spec_supply_price'] = $val['spec_supply_price'];
            $temp['discount_spec_price'] = $val['discount_spec_price'];
            $temp['is_show_discount'] = $val['is_show_discount'];

            //判断是添加还是修改内容的一个处理
            if($spec_id==0)
            {
                $f = $model_spec->add($temp);
                $yes_spec_ids[] = $f;
                $spec_id = $f;
            }
            else
            {
                $f = $model_spec->edit($spec_id,$temp);
                $yes_spec_ids[] = $spec_id;
            }

            if(!$f)
            {
                $this->_error('添加规格的时候出错了');
                return false;
            }
            if(empty($spec))
            {
                $spec = $temp;
                $spec['spec_id'] = $spec_id;
            }


        }

        /**
         * 清除其他的数据
         */
        $sql = "delete from {$this->_prefix}goods_spec where goods_id ='{$this->goods_id}' and spec_id not in (". implode(',',$yes_spec_ids) .") ";
        $this->query($sql);


        return $spec;

    }


    protected function addattr($attr_data,$goods_id)
    {
        $model_attr = m('goodsattr');

        //找到原来的老数据
        $old_data = $model_attr->find("goods_id='{$this->goods_id}' and attr_id not in (1,2,3) ");
        $old_ids = array();
        foreach($old_data as $val)
        {
            $old_ids[$val['attr_id']] = $val['gattr_id'];
        }

        $yes_ids = array(0);
        //添加对应的属性值的处理
        foreach($attr_data as $val)
        {
            $attr_id = isset($old_ids[$val['pid']])?$old_ids[$val['pid']]:0;

            $temp = array('goods_id'=>$goods_id,'attr_name'=>$val['name'],'attr_value'=>$val['value'],'attr_id'=>$val['pid']);
            if($attr_id == 0)
            {
                $f = $model_attr->add($temp);
                $yes_ids[]= $f;
            }
            else
            {
                $f = $model_attr->edit($attr_id,$temp);
                $yes_ids[] = $attr_id;
            }

            if(!$f)
            {
                $this->_error('添加商品属性的时候发生错误');
                return false;
            }
        }

        //清除不必要的数据内容

        $sql = "delete from {$this->_prefix}goods_attr where goods_id='{$goods_id}' and gattr_id not in (". implode(',',$yes_ids) .") ";
        $this->query($sql);

        return true;
    }

    /**
     * @param $images
     * @param $default
     * @param $goods_id
     * @return bool
     *
     * 保存商品图片，并且删除不需要的商品图片
     */
    public function add_goods_images($images,$default,$goods_id)
    {
        $model_image = m('goodsimage');
        $image_list = $model_image->find(array('conditions'=>"goods_id='{$goods_id}'"));
        $old_image_data = array();

        foreach($image_list as $val)
        {
            $old_image_data[$val['image_id']] = $val['image_url'];
        }
        //找到
        $old_image_map = array_flip($old_image_data);

        $yes_image_ids = array(0);
        $sort = 1;
        $this->begin();
        $images[] = $default;
        $images = array_unique($images);
        foreach($images as $val)
        {
            $images_id = isset($old_image_map[$val])?$old_image_map[$val]:0;
            $temp = array();
            $temp['image_url'] = $val;
            $temp['thumbnail'] = $val;
            $temp['goods_id'] = $goods_id;
            $sort++;

            if($val == $default)
            {
                $temp['sort_order'] = 1;
            }
            else
            {
                $temp['sort_order'] = $sort;
            }

            if($images_id)
            {
                $flag = $model_image->edit($images_id,$temp);
                $yes_image_ids[] = $images_id;
            }
            else
            {
                $flag = $model_image->add($temp);
                $yes_image_ids[] = $flag;
            }

            if(!$flag)
            {
                $this->_error('处理图片时发生错误');
                $this->rollback();
                return false;
            }
        }

        //删除不用的图片
        $sql = "delete from ".$this->_prefix."goods_image  where goods_id='{$goods_id}' and image_id not in (". implode(',',$yes_image_ids) .") ";

        $flag = $this->query($sql);
        if(!$flag)
        {
            $this->_error('处理图片时发生错误');
            $this->rollback();
            return false;
        }
        $this->commit();
        return true;
    }

    /**
     * @param $data
     * @return bool
     *
     * 检查数据的正确性
     */
    public function check_data(&$data,$step=null)
    {
        //分类数据的正确性
        if($step)
        {
            $method = "check_data_{$step}";
            if(method_exists($this,$method))
            {
                return $this->{$method}($data);
            }
            else
            {
                $this->_error("不存在的方法验证错误");
                return false;
            }
        }


        $this->_error('无效的验证错误信息');
        return false;

        return true;

    }

    /**
     * 第一步检测
     */
    protected function check_data_1(&$data)
    {
        //分类是否到最后一级了，并且符合正确的分类规则
        $model_cate = m('gcategory');
        $model_cateb = new GcategoryBModel(array(),$model_cate->db);
        //看是否为最后一级
        $flag = $model_cateb->is_leaf($data['cate_id']);
        if(!$flag)
        {
            $this->_error('分类信息不是最后一级');
            return false;
        }

        $cateinfo = $model_cateb->self_parent_info($data['cate_id']);
        //var_dump($data['cate_id']);exit;
        if(empty($cateinfo))
        {
            $this->_error('商品分类一，不可以为空');
            return false;
        }
        $data['cate_id_1'] = 0;
        $data['cate_id_2'] = 0;
        $data['cate_id_3'] = 0;
        $data['cate_id_4'] = 0;
        $data['cate_name'] = '';
        $int = 0;
        $names = array();
        foreach($cateinfo as $key=>$val)
        {
            if($int == 4)
            {
                break;
            }
            $int++;
            $data["cate_id_{$int}"] = $val['cate_id'];
            $names[] = $val['cate_name'];
        }
        $data['cate_name'] = implode("\t",$names);

        //
        $data['cate_id2_1'] = 0;
        $data['cate_id2_2'] = 0;
        $data['cate_id2_3'] = 0;
        $data['cate_id2_4'] = 0;
        $data['cate_name2'] = '';

        if($data['cate_id2'])
        {
            $flag = $model_cateb->is_leaf($data['cate_id2']);
            if(!$flag)
            {
                $this->_error('分类二信息不是最后一级');
                return false;
            }

            $cateinfo = $model_cateb->self_parent_info($data['cate_id2']);
            if(empty($cateinfo))
            {
                $this->_error('分类信息2无效');
                return false;
            }

            $int = 0;
            $names = array();
            foreach($cateinfo as $key=>$val)
            {
                if($int == 4)
                {
                    break;
                }
                $int++;
                $data["cate_id2_{$int}"] = $val['cate_id'];
                $names[] = $val['cate_name'];
            }
            $data['cate_name2'] = implode("\t",$names);

        }
        else
        {
            $data['cate_id2'] = 0;
            $data['cate_id2_1'] = 0;
            $data['cate_id2_2'] = 0;
            $data['cate_id2_3'] = 0;
            $data['cate_id2_4'] = 0;
            $data['cate_name2'] = '';
        }

        if($data['sgcate_id'] && is_array($data['sgcate_id']))
        {
            $temp = (array)$model_cate->find(array('conditions'=>"store_id='{$this->store_id}' and cate_id in (". implode(',',$data['sgcate_id']) .")"));

            $data['sgcate_id'] = array_keys($temp);
        }
        else
        {
            $data['sgcate_id'] = array();
        }


        //检测本店分类是否属于自己的扩展信息是否属于自己
        return true;
    }

    protected function check_data_2(&$data)
    {
        //品牌的可用性校验

        $data['brand_id'] = intval($data['brand_id']);


        //有效性的处理
        $model_brand = m('brand');
        $brand_data = $model_brand->get(array('conditions'=>"brand_id = {$data['brand_id']} "));
        if(empty($brand_data))
        {
            $this->_error('请选择有效的商品信息');
            return false;
        }

        $temp = array($brand_data['brand_name'],$brand_data['en_name']);
        $temp = array_filter($temp);
        $data['brand'] = implode("\t",$temp);

        //标签的过滤处理
        $data['tags'] = trim($data['tags']);
        if(empty($data['tags']))
        {
            $this->_error("标签不可为空");
            return false;
        }

        $data['introduction'] = trim($data['introduction']);
        if(empty($data['introduction']))
        {
            $this->_error("商品简介不可为空");
            return false;
        }

        if($data['tags'])
        {
            $data['tags'] = str_ireplace('，',',',$data['tags']);
        }

        $data['attr_1'] = trim($data['attr_1']);
        $data['attr_2'] = trim($data['attr_2']);
        $data['attr_3'] = trim($data['attr_3']);
        //其他属性的过滤处理

        return true;
    }

    protected function check_data_3(&$data)
    {
        //图片是否是自己的一个过滤处理
        //图片传上来应该是对应的id号
        //如果商品不是外站链接，那么就会严格检查图片的路径问题

        (array)$data['image_list'];
        //检查图片的路径
        if(!empty($data['image_list']) && $this->check_goods_image_path)
        {
            $image_list = $data['image_list'];
            $model_list = m('uploadedfile');
            if($this->goods_id)
            {

            }
            elseif($this->gt_id)
            {

            }


        }

        return true;

    }

    protected function check_data_4(&$data)
    {
        //必填信息的校验
        $data['market_price'] = floatval($data['market_price']);
        $data['price_g'] = floatval($data['price_g']);
        $data['rate'] = floatval($data['rate']);
        $mkey = array('market_price'=>'市场价','price_g'=>'本店价','rate'=>'扣点');
        foreach($mkey as $k=>$v)
        {
            if($data[$k]<=0)
            {
                $this->_error("{$v}无效");
                return false;
            }
        }

        if($data['supply_price']<0)
        {
            $this->_error("供货价无效");
            return false;
        }

        if($data['rate']<5 || $data['rate']>99)
        {
            $this->_error("扣点无效（5-99）");
            return false;
        }

        if($data['market_price']<$data['price_g'])
        {
            $this->_error("平台价不可高于市场价");
            return false;
        }

        $is_act = $data['is_act']==1;

        //是否选择运费模板
        if($data['post_template_id'])
        {
            //验证有效性
            if(empty($data['post_template_value']))
            {
                $this->_error("请填写运费单位");
                return false;
            }
        }
        else
        {
            $data['post_template_value'] = '';
        }

        $data['act_rate'] = intval($data['act_rate']);
        if($is_act == 1 )
        {
            if( empty($data['activity_name']))
            {
                $this->_error("优惠名称不能为空");
                return false;
            }

            $data['act_end_time'] = empty($data['act_end_time'])?0:strtotime("{$data['act_end_time']}:00");
            $data['act_start_time'] = empty($data['act_start_time'])?0:strtotime("{$data['act_start_time']}:00");
            $data['act_start_time'] = intval($data['act_start_time']);
            $data['act_end_time'] = intval($data['act_end_time']);
            if($data['act_end_time']<=0 || $data['act_start_time']<=0)
            {
                $this->_error("请设置优惠时间段");
                return false;
            }
            if($data['act_end_time']>0 && $data['act_start_time']>0 && $data['act_start_time']>=$data['act_end_time'])
            {
                $this->_error("开始时间不能大于结束时间");
                return false;
            }
            if($data['act_rate']<5 || $data['act_rate']>99)
            {
                $this->_error("优惠扣点无效(5-99)");
                return false;
            }
        }
        else
        {
            $data['activity_name']='';
            $data['act_end_time'] = 0;
            $data['act_start_time'] = 0;
            $data['act_rate'] = 0;
        }

        if(!empty($data['activity_name']))
        {
            $utf8_length = mb_strlen($data['activity_name'],'UTF8');
            //计算长度
            if($utf8_length>0)
            {
                $pattern = "/[\x{4e00}-\x{9fa5}]+/u";
                preg_match_all($pattern,$data['activity_name'],$result,PREG_PATTERN_ORDER);
                $ch_length = 0;
                if(!empty($result))
                {
                    foreach($result[0] as $val)
                    {
                        $ch_length+= mb_strlen($val,'UTF8');
                    }
                }

                $utf8_length+=$ch_length;

            }

            if($utf8_length>12)
            {
                $this->_error('活动名称不可超过6个汉字(12个字符)');
                return false;
            }
        }

        //价格扣点等信息

        foreach($data['sku_data'] as $key=> $val)
        {
            if($is_act == 1)
            {
                $val['discount_spec_price'] = $is_act==1?($val['discount_spec_price']>0?$val['discount_spec_price']:$data['discount_price']):0;
                $val['discount_spec_price'] = max(0,$val['discount_spec_price']);
                $val['is_show_discount'] = 2;

                if($val['discount_spec_price']<=0)
                {
                    $this->_error("优惠价格无效");
                    return false;
                }

                //var_dump($val);exit;
            }
            else
            {
                $val['is_show_discount'] = 1;
                $val['discount_spec_price'] = 0;
            }

            if($val['price']<=0)
            {
                $this->_error("商品规格价格无效");
                return false;
            }

            if($val['stock']<0)
            {
                $this->_error("库存规格无效");
                return false;
            }


            if($val['spec_supply_price']<0)
            {
                $this->_error("供货价无效");
                return false;
            }
            if($is_act)
            {
                if($val['discount_spec_price']<=0)
                {
                    $this->_error("优惠价无效");
                    return false;
                }

                if( $val['discount_spec_price'] >= $val['price'] )
                {
                    $this->_error("优惠价格不能高于售价");
                    return false;
                }
            }

            $data['sku_data'][$key] = $val;

        }

        //规格数量
        $temp = $data['sku_data'];
        $temp_spec = array_pop($temp);
        $spec_temp = array($temp_spec['spec_1'],$temp_spec['spec_2']);

        $spec_temp = array_filter($spec_temp);
        $data['spec_qty'] = count($spec_temp);
        if(empty($temp_spec['spec_1']))
        {
            $data['spec_name_1'] = '';
        }
        if(empty($temp_spec['spec_2']))
        {
            $data['spec_name_2'] = '';
        }

        return true;

    }

    protected function check_data_5(&$data)
    {
        //对详情的处理内容
        $data['description'] = htmlspecialchars($data['description'],ENT_QUOTES);
        return true;
    }


    public function getkey($step)
    {
        $data = array();
        if($step == 1)
        {
            $data = array('cate_id','cate_id2','cate_id_1','cate_id_2','cate_id_3','cate_id_4',
                'cate_id2_1','cate_id2_2','cate_id2_3','cate_id2_4','cate_name','cate_name2');
        }
        elseif($step == 2)
        {
            $data = array('brand_id','goods_name','tags','introduction','brand');
        }
        elseif($step == 3)
        {
            $data = array('default_image');
        }
        elseif($step == 4)
        {
            $data = array('market_price','price','discount_price','market_price','rate',
                'supply_price','post_template_id','post_template_value','is_act','spec_qty',
                'spec_name_1','spec_name_2','activity_name','act_start_time','act_end_time',
                'act_rate','default_spec');
        }
        elseif($step==5)
        {
            $data = array('description');
        }

        return $data;
    }









} 